package com.moyangfenghun.javabase;

/**
 * 消息生产消费者模式
 */
public class MessageBox {
    private String message="";
    private Boolean empty=true;

    public synchronized void produce(String message) {
        while (!empty){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
                Thread.currentThread().interrupt();
            }
        }
        this.message = message;
        empty = false;
        notifyAll();
    }

    public synchronized String consume() {
        while (empty){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
                Thread.currentThread().interrupt();
            }
        }
        empty = true;
        notifyAll();
        return message;
    }
}
